﻿using BW.Mes.WinForms.BasicData;
using BW.Mes.WinForms.Common;
using BW.Mes.WinForms.Process.ProcessModel.Model;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Services.Description;
using System.Windows.Forms;
using static BW.Mes.WinForms.BasicData.CustomerForm;
using static BW.Mes.WinForms.BasicData.LineForm1;
using static BW.Mes.WinForms.BasicData.ProductForm;
using static BW.Mes.WinForms.Process.OperationModel.OperationDataForm;
using static BW.Mes.WinForms.Process.ProcessDataForm;

namespace BW.Mes.WinForms.Production.Order
{
    public partial class AddOrederForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _apiBaseUrl = "http://120.26.197.100:8022";
        private readonly string _apiProcessUrl = "http://120.26.197.100:8022";
        private readonly string _qiniuDomain = "syv7j21aq.hb-bkt.clouddn.com"; // 七牛云存储域名
        private readonly string _qiniuPrefix = "Pic/"; // 七牛云存储前缀目录


        public AddOrederForm()
        {
            InitializeComponent();

            // 添加单选框的CheckedChanged事件处理
            on_off.CheckedChanged += On_off_CheckedChanged;

            // 设置日期控件允许为空
            BeginTime.Properties.NullDate = DateTime.MinValue;
            BeginTime.Properties.NullText = "";
            BeginTime.Properties.AllowNullInput = DevExpress.Utils.DefaultBoolean.True;
            BeginTime.Properties.ShowNullValuePrompt = DevExpress.XtraEditors.ShowNullValuePromptOptions.Default;

            EndTime.Properties.NullDate = DateTime.MinValue;
            EndTime.Properties.NullText = "";
            EndTime.Properties.AllowNullInput = DevExpress.Utils.DefaultBoolean.True;
            EndTime.Properties.ShowNullValuePrompt = DevExpress.XtraEditors.ShowNullValuePromptOptions.Default;

            // 初始化字段
            _httpClient = new HttpClient();
            _apiProcessUrl = "http://120.26.197.100:8022"; // 替换为您的实际API基础URL
            _apiBaseUrl = "http://120.26.197.100:8022";

            //工序路线
            ShowOperation();
            //产品主数据
            ShowMasterData();
            //产线
            ShowLine();
            //客户
            ShowClient();
        }

        #region 照片上传
        private async void Uploading_Click(object sender, EventArgs e)
        {
            try
            {
                // 使用XtraOpenFileDialog选择文件
                xtraOpenFileDialog1.Filter = "图片文件 (*.jpg;*.jpeg;*.png)|*.jpg;*.jpeg;*.png|所有文件 (*.*)|*.*"; // 设置筛选器
                if (xtraOpenFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    // 用户选了文件，可获取路径
                    string filePath = xtraOpenFileDialog1.FileName;

                    try
                    {
                        // 显示上传中提示
                        XtraMessageBox.Show("文件上传中，请稍候...");

                        // 检查文件大小
                        FileInfo fileInfo = new FileInfo(filePath);
                        if (fileInfo.Length > 10 * 1024 * 1024) // 10MB限制
                        {
                            XtraMessageBox.Show("文件大小超过10MB，请选择较小的文件");
                            return;
                        }

                        // 调用WebApi上传图片
                        string imageUrl = await UploadImageToWebApiAsync(filePath);

                        if (!string.IsNullOrEmpty(imageUrl))
                        {
                            // 将文件名显示在按钮上
                            Img.Text = Path.GetFileName(filePath);
                            // 在Img.Tag中保存URL
                            Img.Tag = imageUrl;

                            XtraMessageBox.Show("文件上传成功！");
                        }
                        else
                        {
                            XtraMessageBox.Show("文件上传失败，请稍后重试");
                        }
                    }
                    catch (Exception ex)
                    {
                        XtraMessageBox.Show($"文件上传失败：{ex.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"上传文件时发生错误：{ex.Message}");
            }
        }
        /// <summary>
        /// 通过WebApi上传图片到七牛云
        /// </summary>
        /// <param name="filePath">本地文件路径</param>
        /// <returns>上传成功返回图片URL，失败返回null</returns>
        private async Task<string> UploadImageToWebApiAsync(string filePath)
        {
            try
            {
                // 创建MultipartFormDataContent
                using (var content = new MultipartFormDataContent())
                {
                    // 读取文件内容
                    byte[] fileBytes = File.ReadAllBytes(filePath);
                    var fileContent = new ByteArrayContent(fileBytes);

                    // 添加文件内容到请求
                    content.Add(fileContent, "file", Path.GetFileName(filePath));

                    // 创建HttpClient
                    using (var client = new HttpClient())
                    {
                        // 设置WebApi基地址
                        client.BaseAddress = new Uri(_apiBaseUrl);

                        // 发送请求
                        var response = await client.PostAsync("/T4/ProduceModel/UploadImages", content);

                        // 检查响应状态
                        if (response.IsSuccessStatusCode)
                        {
                            // 读取响应内容
                            string responseContent = await response.Content.ReadAsStringAsync();

                            // 如果响应是纯文本（文件名），直接构建URL
                            if (!string.IsNullOrEmpty(responseContent) && !responseContent.StartsWith("{"))
                            {
                                // 假设响应内容是文件名，需要构建完整URL
                                string fileName = responseContent.Trim();
                                string imageUrl = $"http://{_qiniuDomain}/{_qiniuPrefix}{fileName}"; // 使用配置的七牛云域名和前缀
                                return imageUrl;
                            }

                            // 如果是JSON格式，尝试解析
                            if (responseContent.StartsWith("{"))
                            {
                                var result = JsonConvert.DeserializeObject<UploadResult>(responseContent);
                                if (result != null && result.Success && !string.IsNullOrEmpty(result.Url))
                                {
                                    return result.Url;
                                }
                            }

                            // 返回原始响应作为备选
                            if (!string.IsNullOrEmpty(responseContent))
                            {
                                return responseContent.Trim();
                            }
                        }

                        return null;
                    }
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 上传结果类
        /// </summary>
        private class UploadResult
        {
            public string Url { get; set; }
            public bool Success { get; set; }
            public string Message { get; set; }
        }


        #endregion


        /// <summary>
        /// 添加工单的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void AddOrdeAction_Click(object sender, EventArgs e)
        {
            try
            {
                if (Client.EditValue == null)
                {
                    XtraMessageBox.Show("请选择客户");
                    return;
                }

                if (Line.EditValue == null)
                {
                    XtraMessageBox.Show("请选择产线");
                    return;
                }

                if (Masterdata.EditValue == null)
                {
                    XtraMessageBox.Show("请选择产品主数据");
                    return;
                }

                if (Operation.EditValue == null)
                {
                    XtraMessageBox.Show("请选择工序路线");
                    return;
                }

                // 处理图片路径
                string imgPath = null;
                if (Img.Tag != null)
                {
                    imgPath = Img.Tag.ToString();

                    // 检查是否为本地路径
                    if (imgPath.StartsWith("Images/"))
                    {
                        // 确保本地文件存在
                        string fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, imgPath);
                    }
                }
                else if (!string.IsNullOrEmpty(Img.Text))
                {
                    // 如果没有Tag但有Text，可能是直接输入的文件名
                    imgPath = Img.Text;
                }

                var model = new OrderForm
                {
                    Code = Code.Text,
                    ProductionType = ProductionType.Text,
                    // 修改这一行，使用EditValue获取客户ID
                    Client = Client.EditValue != null ? Convert.ToInt64(Client.EditValue) : 0,
                    //产品主数据
                    Masterdata = Masterdata.EditValue != null ? Convert.ToInt64(Masterdata.EditValue) : 0,
                    // 使用EditValue获取选中的ID值  产线
                    Line = Line.EditValue != null ? Convert.ToInt64(Line.EditValue) : 0,
                    //工序路线 Operation
                    Operation = Operation.EditValue != null ? Convert.ToInt64(Operation.EditValue) : 0,

                    ProductionCount = !string.IsNullOrWhiteSpace(ProductionCount.Text) && int.TryParse(ProductionCount.Text, out int count) ? count : 0,
                    BeginTime = BeginTime.EditValue != null ? (DateTime)BeginTime.EditValue : DateTime.MinValue,
                    EndTime = EndTime.EditValue != null ? (DateTime)EndTime.EditValue : DateTime.MinValue,
                    Whether = Whether.Text,
                    Img = imgPath, // 使用处理后的图片路径
                    ProductionDesc = ProductionDesc.Text,
                    CreatedBy = RequestUser.InputUserName,
                };

                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022");

                    var json = JsonConvert.SerializeObject(model);

                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    var response = await client.PostAsync("/T4/ProduceModel/AddWorkorder", content);

                    if (response.IsSuccessStatusCode)
                    {
                        var responseContent = await response.Content.ReadAsStringAsync();

                        XtraMessageBox.Show("添加成功！");
                        this.Close();
                    }
                    else
                    {
                        var errorContent = await response.Content.ReadAsStringAsync();
                        XtraMessageBox.Show($"添加失败：{response.StatusCode} - {errorContent}");
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"添加工单时发生错误：{ex.Message}");
            }
        }

        #region 下拉框数据加载
        /// <summary>
        /// 工序路线下拉
        /// </summary>
        /// <returns></returns>
        private async Task ShowOperation()
        {
            HttpResponseMessage response = await _httpClient.GetAsync($"{_apiProcessUrl}/T5/OperationModel/ShowOperation");
            response.EnsureSuccessStatusCode();


            string responseBody = await response.Content.ReadAsStringAsync();
            var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

            if (jsonObject["pagingData"] != null)
            {
                string dataJson = jsonObject["pagingData"].ToString();
                var process = JsonConvert.DeserializeObject<List<OperationModel>>(dataJson);

                // 设置数据源
                Operation.Properties.DataSource = process;
                // 在加载产线数据时
                Operation.Properties.ValueMember = "Id";  // 数据源中的主键字段名
                Operation.Properties.DisplayMember = "OperationName";  // 数据源中的显示文本字段名
                Operation.Properties.NullText = "请选择工序路线";

                // 配置GridLookUpEdit的列 - 使用正确的方式
                if (Operation.Properties.PopupView is DevExpress.XtraGrid.Views.Grid.GridView gridView)
                {

                    // 清除现有列
                    gridView.Columns.Clear();



                    // 添加产线名称列
                    DevExpress.XtraGrid.Columns.GridColumn nameColumn = new DevExpress.XtraGrid.Columns.GridColumn();
                    nameColumn.Caption = "工序路线";
                    nameColumn.FieldName = "OperationName";
                    nameColumn.Visible = true;
                    nameColumn.VisibleIndex = 0;

                    // 可选：设置列宽
                    nameColumn.Width = 150;

                    // 添加列到网格视图
                    gridView.Columns.Add(nameColumn);

                    // 禁用网格视图的分组面板
                    gridView.OptionsView.ShowGroupPanel = false;

                    // 设置行焦点样式
                    gridView.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;

                    // 禁用单元格焦点外观
                    gridView.OptionsSelection.EnableAppearanceFocusedCell = false;
                }
            }

        }

        /// <summary>
        /// 产品主数据下拉
        /// </summary>
        /// <returns></returns>
        private async Task ShowMasterData()
        {
            HttpResponseMessage response = await _httpClient.GetAsync($"{_apiBaseUrl}/T2/Product/GetProduct");
            response.EnsureSuccessStatusCode();


            string responseBody = await response.Content.ReadAsStringAsync();
            var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

            if (jsonObject["pageDatas"] != null)
            {
                string dataJson = jsonObject["pageDatas"].ToString();
                var process = JsonConvert.DeserializeObject<List<ProductModel>>(dataJson);

                // 设置数据源
                Masterdata.Properties.DataSource = process;
                // 在加载产线数据时
                Masterdata.Properties.ValueMember = "Id";  // 数据源中的主键字段名
                Masterdata.Properties.DisplayMember = "ProductName";  // 数据源中的显示文本字段名
                Masterdata.Properties.NullText = "请选择产品主数据";

                // 配置GridLookUpEdit的列 - 使用正确的方式
                if (Masterdata.Properties.PopupView is DevExpress.XtraGrid.Views.Grid.GridView gridView)
                {

                    // 清除现有列
                    gridView.Columns.Clear();



                    // 添加产线名称列
                    DevExpress.XtraGrid.Columns.GridColumn nameColumn = new DevExpress.XtraGrid.Columns.GridColumn();
                    nameColumn.Caption = "产品主数据";
                    nameColumn.FieldName = "ProductName";
                    nameColumn.Visible = true;
                    nameColumn.VisibleIndex = 0;

                    // 可选：设置列宽
                    nameColumn.Width = 150;

                    // 添加列到网格视图
                    gridView.Columns.Add(nameColumn);

                    // 禁用网格视图的分组面板
                    gridView.OptionsView.ShowGroupPanel = false;

                    // 设置行焦点样式
                    gridView.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;

                    // 禁用单元格焦点外观
                    gridView.OptionsSelection.EnableAppearanceFocusedCell = false;
                }
            }

        }

        /// <summary>
        /// 产线下拉
        /// </summary>
        /// <returns></returns>
        private async Task ShowLine()
        {
            HttpResponseMessage response = await _httpClient.GetAsync($"{_apiBaseUrl}/T2/Line/GetLine");
            response.EnsureSuccessStatusCode();


            string responseBody = await response.Content.ReadAsStringAsync();
            var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

            if (jsonObject["pageDatas"] != null)
            {
                string dataJson = jsonObject["pageDatas"].ToString();
                var process = JsonConvert.DeserializeObject<List<LineModel>>(dataJson);

                // 设置数据源
                Line.Properties.DataSource = process;
                // 在加载产线数据时
                Line.Properties.ValueMember = "Id";  // 数据源中的主键字段名
                Line.Properties.DisplayMember = "LineName";  // 数据源中的显示文本字段名
                Line.Properties.NullText = "请选择所属产线";

                // 配置GridLookUpEdit的列 - 使用正确的方式
                if (Line.Properties.PopupView is DevExpress.XtraGrid.Views.Grid.GridView gridView)
                {

                    // 清除现有列
                    gridView.Columns.Clear();



                    // 添加产线名称列
                    DevExpress.XtraGrid.Columns.GridColumn nameColumn = new DevExpress.XtraGrid.Columns.GridColumn();
                    nameColumn.Caption = "产线名称";
                    nameColumn.FieldName = "LineName";
                    nameColumn.Visible = true;
                    nameColumn.VisibleIndex = 0;

                    // 可选：设置列宽
                    nameColumn.Width = 150;

                    // 添加列到网格视图
                    gridView.Columns.Add(nameColumn);

                    // 禁用网格视图的分组面板
                    gridView.OptionsView.ShowGroupPanel = false;

                    // 设置行焦点样式
                    gridView.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;

                    // 禁用单元格焦点外观
                    gridView.OptionsSelection.EnableAppearanceFocusedCell = false;
                }
            }

        }

        /// <summary>
        /// 客户下拉
        /// </summary>
        /// <returns></returns>
        private async Task ShowClient()
        {
            HttpResponseMessage response = await _httpClient.GetAsync($"{_apiBaseUrl}/T2/Customer/GetCustomer");
            response.EnsureSuccessStatusCode();


            string responseBody = await response.Content.ReadAsStringAsync();
            var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

            if (jsonObject["pageDatas"] != null)
            {
                string dataJson = jsonObject["pageDatas"].ToString();
                var process = JsonConvert.DeserializeObject<List<CustomerModel>>(dataJson);

                // 设置数据源
                Client.Properties.DataSource = process;
                // 在加载产线数据时
                Client.Properties.ValueMember = "Id";  // 数据源中的主键字段名
                Client.Properties.DisplayMember = "CustomerName";  // 数据源中的显示文本字段名
                Client.Properties.NullText = "请选择所属客户";

                // 配置GridLookUpEdit的列 - 使用正确的方式
                if (Client.Properties.PopupView is DevExpress.XtraGrid.Views.Grid.GridView gridView)
                {
                    // 清除现有列
                    gridView.Columns.Clear();

                    // 添加产线名称列
                    DevExpress.XtraGrid.Columns.GridColumn nameColumn = new DevExpress.XtraGrid.Columns.GridColumn();
                    nameColumn.Caption = "客户名称";
                    nameColumn.FieldName = "CustomerName";
                    nameColumn.Visible = true;
                    nameColumn.VisibleIndex = 0;

                    // 可选：设置列宽
                    nameColumn.Width = 150;

                    // 添加列到网格视图
                    gridView.Columns.Add(nameColumn);

                    // 禁用网格视图的分组面板
                    gridView.OptionsView.ShowGroupPanel = false;

                    // 设置行焦点样式
                    gridView.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;

                    // 禁用单元格焦点外观
                    gridView.OptionsSelection.EnableAppearanceFocusedCell = false;
                }
            }
        }
        #endregion


        /// <summary>
        /// 实体类
        /// </summary>
        public class OrderForm
        {
            /// <summary>
            /// 编码
            /// </summary>
            public string Code { get; set; }
            /// <summary>
            /// 类型  （正常、自建工单）
            /// </summary>
            public string ProductionType { get; set; }

            /// <summary>
            /// 客户  （外键）
            /// </summary>
            public long Client { get; set; }
            /// <summary>
            /// 产品主数据(外键)
            /// </summary>
            public long Masterdata { get; set; }
            /// <summary>
            /// 产线 （外键）
            /// </summary>
            public long Line { get; set; }
            /// <summary>
            /// 工序路线 （外键）
            /// </summary>
            public long Operation { get; set; }

            /// <summary>
            /// 工序进度
            /// </summary>
            public string Progress { get; set; }
            /// <summary>
            /// 数量
            /// </summary>
            public int ProductionCount { get; set; }
            /// <summary>
            /// 开始时间
            /// </summary>
            public DateTime BeginTime { get; set; }
            /// <summary>
            /// 结束时间
            /// </summary>
            public DateTime EndTime { get; set; }
            /// <summary>
            /// 是否允许有跳工序
            /// </summary>
            public string Whether { get; set; }
            /// <summary>
            /// 上传文件
            /// </summary>
            public string Img { get; set; }
            /// <summary>
            /// 备注
            /// </summary>
            public string ProductionDesc { get; set; }

            /// <summary>
            /// 添加人
            /// </summary>
            public string CreatedBy { get; set; }
        }
        /// <summary>
        /// 单选框状态变化事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void On_off_CheckedChanged(object sender, EventArgs e)
        {
            if (on_off.Checked)
            {
                // 勾选时，生成以MO开头+年月日+四位随机数的编码
                string datePrefix = DateTime.Now.ToString("yyyyMMdd");
                string randomNumber = GenerateRandomNumber(4);
                Code.Text = $"MO{datePrefix}{randomNumber}";

                // 设置Code文本框为不可编辑且不可选中
                Code.Properties.ReadOnly = true;
                Code.Enabled = false;  // 禁用控件，使其不可选中
            }
            else
            {
                // 未勾选时，清空文本框
                Code.Text = string.Empty;

                // 设置Code文本框为可编辑
                Code.Properties.ReadOnly = false;
                Code.Enabled = true;   // 启用控件
            }
        }
        // 生成指定位数的随机数字字符串
        private string GenerateRandomNumber(int digits)
        {
            Random random = new Random();
            int minValue = (int)Math.Pow(10, digits - 1);
            int maxValue = (int)Math.Pow(10, digits) - 1;
            int randomNum = random.Next(minValue, maxValue);
            return randomNum.ToString();
        }
        /// <summary>
        /// 重置按钮点击事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Reset_Click(object sender, EventArgs e)
        {
            // 重置所有输入字段
            Code.Text = string.Empty;
            ProductionType.Text = string.Empty;
            Client.EditValue = null;
            Masterdata.Text = string.Empty;
            Line.EditValue = null;
            Operation.Text = string.Empty;
            ProductionCount.Text = string.Empty;

            // 重置日期为空
            BeginTime.EditValue = null;
            EndTime.EditValue = null;

            // 重置其他字段
            Whether.Text = string.Empty;
            Img.Text = string.Empty;
            ProductionDesc.Text = string.Empty;

            // 重置自动生成编码复选框
            on_off.Checked = false;

            // 确保Code控件可编辑
            Code.Properties.ReadOnly = false;
            Code.Enabled = true;
        }


    }
}